import axios from 'axios';
import config from '@/config/index'
import { createPinia } from 'pinia'
import useAuthStore from '@/stores/useAuthStore';
import router from '../router'
import {ElMessage} from "element-plus";
import useUserStore from "@/stores/useUserStore";
const authStore = useAuthStore(createPinia());
const userStore = useUserStore(createPinia());

// axios.defaults.timeout = 60000;
console.log(!config.mockjs_status)
console.log('[EsAjax] config.mockjs_status = ', config.mockjs_status,import.meta.env.VITE_MOCKJS_STATUS, import.meta.env.VITE_HTTP_BASE_URL)
if (!config.mockjs_status) {
    // mockjs 不支持 baseUrl
    axios.defaults.baseURL = import.meta.env.VITE_HTTP_BASE_URL || 'http://127.0.0.1:8101';
}

axios.interceptors.request.use(option => {
    option.headers.Authorization = authStore.getToken();
    return option;
})

axios.interceptors.response.use(res => {
    if (res.data.code === 300) {
        authStore.setToken('');
        userStore.clear()
        router.push('/login').then(()=>{
           ElMessage.error('登录失效')
        });
    }else{
        return Promise.resolve(res);
    }
}, error => {
    console.log(error)
    return Promise.resolve({data:{message:"系统错误",msg:'系统错误',code:401}});
})

export default axios;
